package com.topvision.common.utils;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

/**
 *
 * @Title: RestUtil
 * @Package com.topvision.common.utils
 * @Description: TODO
 * @author shengwm
 * @date 2017/5/23 15:49
 * @version V0.0.1
 */
public class RestUtil {

	private static Logger logger = LoggerFactory.getLogger(RestUtil.class);

	public static boolean isError(HttpStatus status) {
		HttpStatus.Series series = status.series();
		return (HttpStatus.Series.CLIENT_ERROR.equals(series) || HttpStatus.Series.SERVER_ERROR.equals(series));
	}

	private static CloseableHttpClient createHttpClient(String userName, String password) {
		HttpClientBuilder cb = HttpClientBuilder.create().disableAutomaticRetries();
		cb.setHostnameVerifier(new AllowAllHostnameVerifier());
		// 设置http的基本认证机制
		if (StringUtils.isNotBlank(userName) && StringUtils.isNoneBlank(password)) {
			CredentialsProvider cp = new BasicCredentialsProvider();
			cp.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password));
			cb.setDefaultCredentialsProvider(cp);
		}
		RequestConfig cfg = RequestConfig.custom().setConnectTimeout(300).build();
		cb.setDefaultRequestConfig(cfg);
		return cb.build();
	}

	public static RestTemplate createRestTemplate(String userName, String password) {
		CloseableHttpClient client = createHttpClient(userName, password);
		ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(client);
		return new RestTemplate(requestFactory);
	}
}